<?php

namespace App\System\Component\View;

class TwigView extends View {
	public $twig;
	public $config;
	private $data = array ();
	function __construct($config = array()) {
		$config_default = array (
				'cache_dir' => false, // 开启缓存
				'debug' => false, // 开启调试模式（dump函数可用）
				'auto_reload' => true,
				'extension' => '.html'  // 默认后缀名
		);
		$this->config = array_merge ( $config_default, $config );
		
		$loader = new \Twig_Loader_Filesystem ( $this->config ['template_dir'] );
		$this->twig = new \Twig_Environment ( $loader, array (
				'cache' => $this->config ['cache_dir'],
				'debug' => $this->config ['debug'],
				'auto_reload' => $this->config ['auto_reload'] 
		) );
	}
	
	/**
	 *
	 * {@inheritdoc}
	 *
	 * @see \App\System\Component\View\View::assign()
	 */
	public function assign($var, $value = NULL) {
		// TODO Auto-generated method stub
		if (is_array ( $var )) {
			foreach ( $var as $key => $val ) {
				$this->data [$key] = $val;
			}
		} else {
			$this->data [$var] = $value;
		}
	}
	
	/**
	 *
	 * {@inheritdoc}
	 *
	 * @see \App\System\Component\View\View::render()
	 */
	public function render($template, $data = array(), $return = FALSE) {
		// TODO Auto-generated method stub
		$template = $this->twig->loadTemplate ( $this->getTemplateName ( $template ) );
		$data = array_merge ( $this->data, $data );
		if ($return === TRUE) {
			return $template->render ( $data );
		} else {
			return $template->display ( $data );
		}
	}
	public function getTempLate($template) {
		// TODO Auto-generated method stub
		return $this->render ( $template, array (), true );
	}
	/**
	 *
	 * {@inheritdoc}
	 *
	 * @see \App\System\Component\View\View::getTemplateName()
	 */
	public function getTemplateName($template) {
		$default_ext_len = strlen ( $this->config ['extension'] );
		if (substr ( $template, - $default_ext_len ) != $this->config ['extension']) {
			$template .= $this->config ['extension'];
		}
		return $template;
	}
	
	/**
	 *
	 * {@inheritdoc}
	 *
	 * @see \App\System\Component\View\View::parse()
	 */
	public function parse($string, $data = array(), $return = FALSE) {
		// TODO Auto-generated method stub
		$string = $this->twig->loadTemplate ( $string );
		$data = array_merge ( $this->data, $data );
		if ($return === TRUE) {
			return $string->render ( $data );
		} else {
			return $string->display ( $data );
		}
	}
}

